using System;
using System.Collections;
using System.Collections.Generic;
using Rilisoft.MiniJson;
using UnityEngine;

public class JSONManager : MonoBehaviour
{
	public const int COUNT_ATTEMPT_LOAD_TIME = 3;

	private const string keyFile = "JSONFile_";

	private const string keyHash = "JSONHash_";

	private const string bcwConfig = "bcw-config/";

	private bool hashDownloaded;

	private SaveInt serverTime;

	private static string bcwAction = "http://bcwserver.com/blockcity/action.php";

	private static JSONManager instance;

	private List<string> urls;

	private Dictionary<string, object> urlsHash;

	private Coroutine refreshTimeCoroutine;

	private bool timeLoad;

	private bool lastTimeLoad;

	private SaveFloat serverTimeOffset;

	public static JSONManager Instance
	{
		get
		{
			if (instance == null)
			{
				GameObject gameObject = new GameObject();
				gameObject.name = "JSONManager";
				gameObject.AddComponent<JSONManager>();
			}
			return instance;
		}
	}

	public int lastTimeInGameOnline
	{
		get
		{
			return BCWStorage.Get<int>("LastTimeInGameOnline");
		}
		set
		{
			BCWStorage.Set("LastTimeInGameOnline", value, true);
		}
	}

	public event Action serverTimeUpdate;

	private void SetValue(string keyUrl, string json, string hash)
	{
		BCWStorage.Set("JSONFile_" + keyUrl, json);
		BCWStorage.Set("JSONHash_" + keyUrl, hash);
	}

	private IEnumerator DownloadSignaturesCoroutine(List<string> urls)
	{
		try
		{
			if (urls.Count == 0)
			{
				yield break;
			}
			List<string> names = new List<string>();
			for (int i = 0; i < urls.Count; i++)
			{
				names.Add(GetServerPath(urls[i]));
			}
			string namesSerialized = Json.Serialize(names);
			WWWForm form = new WWWForm();
			form.AddField("app_version", string.Format("{0}:{1}", string.Empty, string.Empty));
			form.AddField("prefix", "bcw-config");
			form.AddField("names", namesSerialized);
			WWW www = new WWW("https://secure.pixelgunserver.com/get_files_info.php", form);
			if (www == null)
			{
				BCWDebug.LogError("Error download file info");
				yield break;
			}
			while (!www.isDone)
			{
				yield return null;
			}
			if (!string.IsNullOrEmpty(www.error))
			{
				BCWDebug.LogError("Error download file info " + www.error);
				yield break;
			}
			urlsHash = Json.Deserialize(www.text) as Dictionary<string, object>;
			hashDownloaded = true;
			foreach (string key in urlsHash.Keys)
			{
				string curUrl = urls[names.IndexOf(key)];
				if (string.IsNullOrEmpty(PlayerPrefs.GetString("JSONHash_" + GetKeyByURL(curUrl))) || !PlayerPrefs.GetString("JSONHash_" + GetKeyByURL(curUrl)).Equals(urlsHash[key] as string))
				{
					StartCoroutine(LoadJSON(urls[names.IndexOf(key)], urlsHash[key] as string));
					yield return null;
				}
			}
			PlayerPrefs.Save();
		}
		finally
		{
		}
	}

	public void UpdateSignature(string url)
	{
		StartCoroutine(DownloadSignaturesCoroutine(new List<string> { url }));
	}

	private void Awake()
	{
		serverTimeOffset = 0f;
		instance = this;
		UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
		urls = new List<string>();
		urls.Add(URLs.CheckVersion);
		urls.Add(URLs.ModSettings);
		urls.Add(URLs.InAppPromo);
		urls.Add(URLs.MarketSales);
		urls.Add(URLs.BestProduct);
		urls.Add(URLs.FriendsSettings);
		urls.Add(URLs.ModeNameSettings);
		urls.Add(URLs.InAppSubscriptions);
		StartCoroutine(DownloadSignaturesCoroutine(urls));
		refreshTimeCoroutine = StartCoroutine(RefreshTime());
	}

	private string GetServerPath(string s)
	{
		return s.Substring(URLs.CheckVersion.IndexOf("bcw-config/") + "bcw-config/".Length);
	}

	private string GetKeyByURL(string url)
	{
		return GetServerPath(url).Replace("/", string.Empty);
	}

	private IEnumerator LoadJSON(string url, string newHash)
	{
		WWW downloadData = new WWW(url);
		while (!downloadData.isDone)
		{
			yield return null;
		}
		string text = string.Empty;
		if (!string.IsNullOrEmpty(downloadData.error))
		{
			BCWDebug.LogError("Download data error from: " + url + " Error: " + downloadData.error);
			yield break;
		}
		PlayerPrefs.SetString("JSONFile_" + GetKeyByURL(url), downloadData.text);
		PlayerPrefs.SetString("JSONHash_" + GetKeyByURL(url), newHash);
	}

	public string GetJSON(string url)
	{
		return PlayerPrefs.GetString("JSONFile_" + GetKeyByURL(url));
	}

	private IEnumerator LoadServerTime()
	{
		settings.UpdateIdPlayer();
		for (int i = 0; i < 3; i++)
		{
			WWWForm form = new WWWForm();
			form.AddField("action", "get_time");
			form.AddField("app_version", BCWServer._version);
			WWW www = new WWW(headers: new Dictionary<string, string> { 
			{
				"Authorization",
				BCWServer.HashForPush(form.data)
			} }, url: bcwAction, postData: form.data);
			while (!www.isDone)
			{
				yield return null;
			}
			if (www != null)
			{
				if (!string.IsNullOrEmpty(www.error))
				{
					BCWDebug.LogError("Error downloading: " + www.error);
				}
				else if (www.text != "fail")
				{
					timeLoad = true;
					int time = 0;
					if (int.TryParse(www.text, out time))
					{
						serverTime = time;
					}
					serverTimeOffset = 0f;
					if (timeLoad != lastTimeLoad && this.serverTimeUpdate != null)
					{
						this.serverTimeUpdate();
					}
					lastTimeLoad = timeLoad;
					yield break;
				}
			}
			yield return new WaitForSeconds(0.5f);
		}
		yield return null;
	}

	private IEnumerator RefreshTime()
	{
		while (true)
		{
			StartCoroutine(LoadServerTime());
			if (!ServerTimeLoad())
			{
				Debug.Log("RefreshTime 5");
				yield return new WaitForSeconds(5f);
			}
			else
			{
				Debug.Log("RefreshTime 600");
				yield return new WaitForSeconds(600f);
			}
		}
	}

	public int GetServerTime()
	{
		if (!timeLoad)
		{
			return 0;
		}
		return (int)serverTime + (int)serverTimeOffset.GetValue();
	}

	public bool ServerTimeLoad()
	{
		return timeLoad;
	}

	private void OnApplicationPause(bool onPause)
	{
		if (!onPause)
		{
			if (timeLoad)
			{
				lastTimeInGameOnline = GetServerTime();
			}
			timeLoad = false;
			lastTimeLoad = false;
			if (refreshTimeCoroutine != null)
			{
				refreshTimeCoroutine = StartCoroutine(RefreshTime());
			}
		}
	}

	private void Update()
	{
		serverTimeOffset = serverTimeOffset.GetValue() + Time.unscaledDeltaTime;
	}
}
